package yxy.game.pm2.module.stairway;

import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;

import yxy.apple.logger.Logger;
import yxy.cherry.data.bean.function;
import yxy.game.pm2.bean.area.AreaGroupBean;
import yxy.game.pm2.bean.timeline.FutureRunnable;
import yxy.game.pm2.module.kow.KowFuture;

import java.util.Collection;

//天梯争霸
public class StairwayFuture extends FutureRunnable {
	protected static Logger logger = Logger.create(StairwayFuture.class);

	@Override
	public void tick() {
		handle();
	}

	@Override
	public long period() {
		return DateTimeConstants.MILLIS_PER_MINUTE * 5;// 10分钟一刷
	}

	@Override
	public void init() {
		handle();
	}

	private void handle() {
		try {
			update();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 状态更新 */
	public void update() {
		logger.info("天梯争雄-状态更新BEGIN");
		Collection<AreaGroupBean> areaGroupBeans = AreaGroupBean.all();
		for (AreaGroupBean areaGroupBean : areaGroupBeans) {
			DateTime now = DateTime.now();
			StairwayModule module = StairwayModule.get(areaGroupBean.getGroupId());
			boolean preState = isOpen(module.getUpdateTime());
			boolean nowState = isOpen(now);
			if (preState == nowState) {
				continue;
			}
			module.setUpdateTime(now);
			module.setOpening(nowState);
			if (nowState) {
				new StairwayHandle().open(module, now);
			} else {
				// 关闭活动 派发邮件奖励
				new StairwayHandle().settle(module);
			}
			module.set();
		}
		logger.info("天梯争雄-状态更新END");
	}

	/** 正式时间循环 */
	static public boolean isOpen(DateTime time) {
		if (time == null) {
			return false;
		}
		int week = time.getDayOfWeek();// 星期
		switch (week) {
			case 6: //周六开始
				return true;
			case 7: //周日结束
				return time.getHourOfDay() < 23;
		}
		return false;
	}

	// XXX TEST 短时测试
//	static private boolean isOpen(DateTime time) {
//		if (time == null) {
//			return false;
//		}
//		// 每日2点开始 23点结束
////		int hour = time.getHourOfDay();
////		return hour >= 2 && hour < 23;
//		// 每小时5分开始
//		int minute = time.getMinuteOfHour();
//		return minute >= 5 && minute <= 59;
//		// 每5分一轮
////		int minute = time.getMinuteOfHour() % 5;
////		return minute >= 2 && minute <= 4;
//	}

}
